#include "Dri_NVS.h"

void Dri_NVS_Init(void)
{
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
}

esp_err_t Dri_NVS_WrriteInt8(char *key, int8_t value)
{
    nvs_handle_t my_handle; 
    esp_err_t err = nvs_open("pwd", NVS_READWRITE, &my_handle);
    if (err != ESP_OK)
        return err;

    err = nvs_set_i8(my_handle, key, value);
    if (err != ESP_OK)
        return err;

    err = nvs_commit(my_handle);
    if (err != ESP_OK)
        return err;

    nvs_close(my_handle);
    return err;
}
esp_err_t Dri_NVS_DelKey(char *key)
{
    nvs_handle_t my_handle;
    esp_err_t err = nvs_open("pwd", NVS_READWRITE, &my_handle);
    if (err != ESP_OK)
        return err;

    err = nvs_erase_key(my_handle, key);
    if (err != ESP_OK)
        return err;

    err = nvs_commit(my_handle);
    if (err != ESP_OK)
        return err;

    nvs_close(my_handle);
    return err;
}
/*
    验证密码
        存储密码    输入密码
        1234    1234    匹配    1234    12123455    匹配
        遍历所以的key
 */
esp_err_t Dri_NVS_IsKeyMatched(char *key)
{

    nvs_handle_t my_handle;
    esp_err_t err = nvs_open("pwd", NVS_READWRITE, &my_handle);
    if (err != ESP_OK)
        return err;

    nvs_iterator_t it = NULL;
    err = nvs_entry_find_in_handle(my_handle, NVS_TYPE_ANY, &it);
    while (err == ESP_OK)
    {
        nvs_entry_info_t info;
        
        nvs_entry_info(it, &info);
        if (strstr(key, info.key))
        {
            err = ESP_OK;
            break;
        }
        err = nvs_entry_next(&it);
    }
    
    nvs_release_iterator(it);
    nvs_close(my_handle);
    return err;
}
